"""
    Controller for marks.
"""

from formencode import validators
from turbogears import widgets, flash
from mnemoply import model
from mnemoply.utils import IdsValidator

from mnemoply.controllers.crud import CRUDController
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.mass_actions import MassAction

class MADelete(MassAction):
    target_class = model.Mark
    name = "mark_delete"
    title = _("Delete selected")

    select_topic_form = widgets.TableForm(
        fields=[
            widgets.HiddenField(
                name="ids",
                validator=IdsValidator(),
            ),
        ],
    )

    def call(self, objs):
        references = []
        for obj in objs:
            references.extend(obj.findReferences())

        if len(references) > 0:
            return dict(
                tg_template="mnemoply.templates.crud.delete_cant",
                references=references,
            )
        else:
            for obj in objs:
                obj.destroySelf()
            flash(_('Records deleted!'))

class MarkController(LookupController, CRUDController):
    model_object = model.Mark
    lookup_columns = [
        TableCol(name='date', caption=_("Date"), size=11),
        TableCol(name='student_groups', caption=_("Groups")),
        TableCol(name='student', caption=_("Student")),
        TableCol(name='topic', caption=_("Topic")),
        TableCol(name='mark_type', caption=_("Mark type")),
        TableCol(name='hours', caption=_("Hours"), hidden=True,
            validator=validators.Int()),
        TableCol(name='comment', caption=_("Comment"), hidden=True),
        ]

    edit_fields = ['date', 'studentID', 'topicID', 'markTypeID', 'hours', 'comment']
    view_fields = edit_fields + ['ownerID']

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource('mark_lookup'),
            columns=self.lookup_columns,
            mass_actions_class=self.model_object,
            title=self.model_object.model_title,
        )
        CRUDController.__init__(self, model_object=self.model_object)

exposed = MarkController()
